// 图表分析页面
const auth = require('../../../utils/auth')
const echarts = require('../../../components/ec-canvas/echarts')
const userApi = require('../../../api/user')
const activitiesApi = require('../../../api/activities')
const complaintsApi = require('../../../api/complaints')
const minLivingAllowanceApi = require('../../../api/minLivingAllowance')
const noticeApi = require('../../../api/notice')

Page({
  data: {
    userInfo: {},
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '管理数据加载中...',
    loading: true,
    
    // 图表配置
    ec: {
      lazyLoad: false
    },
    
    // 存储图表数据的引用（只存储可序列化的数据）
    chartData: {}
  },

  // 存储图表实例的引用（不放在data中，避免循环引用）
  chartInstances: {},

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    this.loadUserInfo()
    this.initChartConfigs()
    this.loadChartData()
  },

  // 初始化图表配置
  initChartConfigs() {
    const that = this
    const chartConfigs = {
      userGrowthChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'user-growth-chart', that.getUserGrowthChartOption)
        }
      },
      userRoleChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'user-role-chart', that.getUserRoleChartOption)
        }
      },
      serviceDistributionChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'service-distribution-chart', that.getServiceDistributionChartOption)
        }
      },
      applicationStatusChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'application-status-chart', that.getApplicationStatusChartOption)
        }
      },
      activityStatusChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'activity-status-chart', that.getActivityStatusChartOption)
        }
      },
      complaintTypeChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'complaint-type-chart', that.getComplaintTypeChartOption)
        }
      },
      monthlyActivityChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'monthly-activity-chart', that.getMonthlyActivityChartOption)
        }
      },
      complaintProcessingChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'complaint-processing-chart', that.getComplaintProcessingChartOption)
        }
      },
      serviceTrendChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'service-trend-chart', that.getServiceTrendChartOption)
        }
      },
      comprehensiveComparisonChart: {
        onInit: function(canvas, width, height, dpr) {
          return that.initChartInstance(canvas, width, height, dpr, 'comprehensive-comparison-chart', that.getComprehensiveComparisonChartOption)
        }
      }
    }
    this.setData(chartConfigs)
  },

  // 初始化图表实例
  initChartInstance(canvas, width, height, dpr, chartId, getOptionFn) {
    if (!echarts || typeof echarts.init !== 'function') {
      console.error('ECharts未正确加载!')
      return null
    }
    
    const devicePixelRatio = dpr || wx.getDeviceInfo().pixelRatio || 1
    
    try {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: devicePixelRatio
      })
      
      canvas.setChart(chart)
      
      // 获取配置并设置
      const option = getOptionFn.call(this)
      chart.setOption(option)
      
      // 存储图表实例引用（不放在data中，避免循环引用）
      if (!this.chartInstances) {
        this.chartInstances = {}
      }
      this.chartInstances[chartId] = chart
      
      // 延迟刷新
      setTimeout(() => {
        chart.resize()
      }, 100)
      
      return chart
    } catch (error) {
      console.error(`初始化图表 ${chartId} 失败:`, error)
      return null
    }
  },

  // 加载用户信息
  loadUserInfo() {
    const role = auth.getCurrentRole()
    if (!role || role !== 'admin') {
      wx.showToast({
        title: '请以管理员身份登录',
        icon: 'none',
        duration: 2000
      })
      
      const tempUserInfo = {
        name: '演示管理员',
        role: 'admin',
        village: '七里营村'
      }
      this.setData({ userInfo: tempUserInfo })
      return
    }
    
    const userInfo = wx.getStorageSync('USER_INFO') || {}
    this.setData({ userInfo })
  },

  // 加载图表数据
  async loadChartData() {
    this.setData({ loading: true })
    this.showGlobalLoading('正在加载图表数据...')
    
    try {
      // 并行获取所有数据
      const [
        userStatsResult,
        userCountResult,
        userListResult,
        activityListResult,
        complaintStatsResult,
        serviceApplicationsResult
      ] = await Promise.allSettled([
        this.loadUserStats(),
        this.loadUserCount(),
        this.loadUserList(), // 新增：获取用户列表用于计算月度增长
        this.loadActivityList(),
        this.loadComplaintStats(),
        this.loadServiceApplications()
      ])

      // 检查是否有500错误
      const results = [
        userStatsResult,
        userCountResult,
        userListResult,
        activityListResult,
        complaintStatsResult,
        serviceApplicationsResult
      ]
      
      const has500Error = results.some(result => {
        if (result.status === 'rejected' && result.reason) {
          const error = result.reason
          return error.status === 500 || (error.message && error.message.includes('500'))
        }
        return false
      })

      if (has500Error) {
        this.setData({ loading: false })
        this.hideGlobalLoading()
        wx.showToast({
          title: '后台服务未启动，请检查服务器状态',
          icon: 'none',
          duration: 3000
        })
        return
      }

      // 整理数据
      const chartData = {
        userStats: userStatsResult.status === 'fulfilled' ? userStatsResult.value : {},
        userCount: userCountResult.status === 'fulfilled' ? userCountResult.value : {},
        userList: userListResult.status === 'fulfilled' ? userListResult.value : [], // 新增：用户列表
        activities: activityListResult.status === 'fulfilled' ? activityListResult.value : [],
        complaintStats: complaintStatsResult.status === 'fulfilled' ? complaintStatsResult.value : {},
        serviceApplications: serviceApplicationsResult.status === 'fulfilled' ? serviceApplicationsResult.value : []
      }

      this.setData({ chartData })
      
      // 延迟初始化图表，确保DOM已渲染
      setTimeout(() => {
        this.setData({ loading: false })
        this.initCharts()
        // 更新所有图表数据
        this.updateAllCharts()
      }, 500)
      
      this.hideGlobalLoading()
    } catch (error) {
      console.error('加载图表数据失败:', error)
      this.setData({ loading: false })
      this.hideGlobalLoading()
      
      // 检查错误状态码
      let errorMessage = '数据加载失败'
      if (error.status === 500) {
        errorMessage = '后台服务未启动，请检查服务器状态'
      } else if (error.type === 'network') {
        errorMessage = '网络连接失败，请检查网络设置'
      } else if (error.status) {
        errorMessage = `请求失败 (${error.status})`
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }
  },

  // 加载用户统计数据
  async loadUserStats() {
    try {
      const result = await userApi.getUserStats()
      return result.success ? result.data : {}
    } catch (error) {
      console.error('获取用户统计失败:', error)
      // 如果是500错误，抛出错误以便统一处理
      if (error.status === 500) {
        throw error
      }
      return {}
    }
  },

  // 加载用户数量
  async loadUserCount() {
    try {
      const result = await userApi.getUserCount()
      return result.success ? result.data : {}
    } catch (error) {
      console.error('获取用户数量失败:', error)
      // 如果是500错误，抛出错误以便统一处理
      if (error.status === 500) {
        throw error
      }
      return {}
    }
  },

  // 加载用户列表（用于计算月度增长）
  async loadUserList() {
    try {
      // 分页获取所有用户，用于计算月度增长数据
      const allUsers = []
      let page = 1
      const pageSize = 100 // 后端限制每页最多100条
      let hasMore = true
      
      while (hasMore) {
        const result = await userApi.getUsers({ page, pageSize })
        if (result.success && result.data) {
          const users = result.data.users || []
          if (users.length > 0) {
            allUsers.push(...users)
          }
          // 检查是否还有更多数据
          const total = result.data.total || 0
          const currentCount = allUsers.length
          // 如果当前页返回的数据少于pageSize，说明已经是最后一页
          if (users.length < pageSize || currentCount >= total) {
            hasMore = false
          } else {
            page++
          }
        } else {
          hasMore = false
        }
      }
      
      return allUsers
    } catch (error) {
      console.error('获取用户列表失败:', error)
      // 如果是500错误，抛出错误以便统一处理
      if (error.status === 500) {
        throw error
      }
      return []
    }
  },

  // 加载活动列表
  async loadActivityList() {
    try {
      // 分页获取所有活动
      const allActivities = []
      let page = 1
      const limit = 100 // 后端限制每页最多100条
      let hasMore = true
      
      while (hasMore) {
        const result = await activitiesApi.getActivityList({ page, limit })
        if (result.success && result.data) {
          const activities = result.data.activities || []
          if (activities.length > 0) {
            allActivities.push(...activities)
          }
          // 检查是否还有更多数据
          const total = result.data.total || 0
          const currentCount = allActivities.length
          // 如果当前页返回的数据少于limit，说明已经是最后一页
          if (activities.length < limit || currentCount >= total) {
            hasMore = false
          } else {
            page++
          }
        } else {
          hasMore = false
        }
      }
      
      return allActivities
    } catch (error) {
      console.error('获取活动列表失败:', error)
      // 如果是500错误，抛出错误以便统一处理
      if (error.status === 500) {
        throw error
      }
      return []
    }
  },

  // 加载投诉统计数据
  async loadComplaintStats() {
    try {
      const result = await complaintsApi.getAdminComplaintStats()
      return result.success ? result.data : {}
    } catch (error) {
      console.error('获取投诉统计失败:', error)
      // 如果是500错误，抛出错误以便统一处理
      if (error.status === 500) {
        throw error
      }
      return {}
    }
  },

  // 加载服务申请数据
  async loadServiceApplications() {
    try {
      // 分页获取所有服务申请
      const allApplications = []
      let page = 1
      const limit = 100 // 后端限制每页最多100条
      let hasMore = true
      
      while (hasMore) {
        const result = await minLivingAllowanceApi.getAllApplications({ page, limit })
        if (result.success && result.data) {
          const applications = result.data.applications || []
          if (applications.length > 0) {
            allApplications.push(...applications)
          }
          // 检查是否还有更多数据
          const total = result.data.total || 0
          const currentCount = allApplications.length
          // 如果当前页返回的数据少于limit，说明已经是最后一页
          if (applications.length < limit || currentCount >= total) {
            hasMore = false
          } else {
            page++
          }
        } else {
          hasMore = false
        }
      }
      
      return allApplications
    } catch (error) {
      console.error('获取服务申请失败:', error)
      // 如果是500错误，抛出错误以便统一处理
      if (error.status === 500) {
        throw error
      }
      return []
    }
  },

  // 初始化图表
  initCharts() {
    console.log('开始初始化所有图表')
    
    const chartIds = [
      'user-growth-chart',
      'user-role-chart',
      'service-distribution-chart',
      'application-status-chart',
      'activity-status-chart',
      'complaint-type-chart',
      'monthly-activity-chart',
      'complaint-processing-chart',
      'service-trend-chart',
      'comprehensive-comparison-chart'
    ]
    
    chartIds.forEach(chartId => {
      const chartComponent = this.selectComponent(`#${chartId}`)
      if (chartComponent) {
        console.log(`初始化图表: ${chartId}`)
        chartComponent.init()
      } else {
        console.warn(`未找到图表组件: ${chartId}`)
      }
    })
  },

  // 更新所有图表数据
  updateAllCharts() {
    const chartInstanceMap = {
      'user-growth-chart': this.getUserGrowthChartOption,
      'user-role-chart': this.getUserRoleChartOption,
      'service-distribution-chart': this.getServiceDistributionChartOption,
      'application-status-chart': this.getApplicationStatusChartOption,
      'activity-status-chart': this.getActivityStatusChartOption,
      'complaint-type-chart': this.getComplaintTypeChartOption,
      'monthly-activity-chart': this.getMonthlyActivityChartOption,
      'complaint-processing-chart': this.getComplaintProcessingChartOption,
      'service-trend-chart': this.getServiceTrendChartOption,
      'comprehensive-comparison-chart': this.getComprehensiveComparisonChartOption
    }
    
    Object.keys(chartInstanceMap).forEach(chartId => {
      const chart = this.chartInstances && this.chartInstances[chartId]
      if (chart) {
        try {
          const option = chartInstanceMap[chartId].call(this)
          chart.setOption(option)
        } catch (error) {
          console.error(`更新图表 ${chartId} 失败:`, error)
        }
      }
    })
  },

  // 用户增长趋势图（折线图）
  getUserGrowthChartOption() {
    // 根据用户列表计算月度增长数据
    const userList = this.data.chartData.userList || []
    const monthlyData = {}
    
    // 统计每个月的用户注册数量（排除管理员）
    userList.forEach(user => {
      if (user.role !== 'admin' && user.createdAt) {
        const date = new Date(user.createdAt)
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
        monthlyData[monthKey] = (monthlyData[monthKey] || 0) + 1
      }
    })
    
    // 获取最近12个月的数据
    const months = []
    const values = []
    const now = new Date()
    
    // 计算累计用户数（从最早的数据开始累计）
    let cumulativeCount = 0
    for (let i = 11; i >= 0; i--) {
      const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
      const monthLabel = `${date.getMonth() + 1}月`
      months.push(monthLabel)
      
      // 累计该月的用户数
      cumulativeCount += monthlyData[monthKey] || 0
      values.push(cumulativeCount)
    }
    
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '8%',
        right: '5%',
        top: '12%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: '#e5e7eb',
            width: 1,
            type: 'solid'
          }
        }
      },
      series: [{
        name: '用户数量',
        type: 'line',
        smooth: true,
        data: values,
        itemStyle: {
          color: '#2c5530'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(44, 85, 48, 0.3)' },
              { offset: 1, color: 'rgba(44, 85, 48, 0.1)' }
            ]
          }
        }
      }]
    }
  },

  // 用户角色分布图（饼图）
  getUserRoleChartOption() {
    const data = this.data.chartData.userCount || {}
    const citizenCount = data.citizenCount || 0
    const adminCount = data.adminCount || 0
    
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        orient: 'horizontal',
        bottom: '5%',
        left: 'center',
        itemGap: 40,
        itemWidth: 14,
        itemHeight: 14,
        textStyle: {
          fontSize: 13,
          color: '#333',
          fontWeight: 'normal'
        }
      },
      series: [{
        name: '用户角色',
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['50%', '42%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          { value: citizenCount, name: '村民', itemStyle: { color: '#2c5530' } },
          { value: adminCount, name: '管理员', itemStyle: { color: '#4a7c59' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          scale: true,
          scaleSize: 5
        }
      }]
    }
  },

  // 服务事项分布图（饼图）
  getServiceDistributionChartOption() {
    // 根据申请类型统计
    const applications = this.data.chartData.serviceApplications || []
    const distribution = {
      '低保申请': 0,
      '其他服务': 0
    }
    
    applications.forEach(app => {
      if (app.type === 'minLivingAllowance' || app.serviceType === '低保申请') {
        distribution['低保申请']++
      } else {
        distribution['其他服务']++
      }
    })
    
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        orient: 'horizontal',
        bottom: '5%',
        left: 'center',
        itemGap: 40,
        itemWidth: 14,
        itemHeight: 14,
        textStyle: {
          fontSize: 13,
          color: '#333',
          fontWeight: 'normal'
        }
      },
      series: [{
        name: '服务类型',
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['50%', '42%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          { value: distribution['低保申请'], name: '低保申请', itemStyle: { color: '#2c5530' } },
          { value: distribution['其他服务'], name: '其他服务', itemStyle: { color: '#4a7c59' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          scale: true,
          scaleSize: 5
        }
      }]
    }
  },

  // 申请状态统计图（柱状图）
  getApplicationStatusChartOption() {
    const applications = this.data.chartData.serviceApplications || []
    const statusCount = {
      'pending': 0,
      'approved': 0,
      'rejected': 0,
      'completed': 0
    }
    
    applications.forEach(app => {
      const status = app.status || 'pending'
      if (statusCount.hasOwnProperty(status)) {
        statusCount[status]++
      }
    })
    
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '8%',
        right: '5%',
        top: '12%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['待处理', '已通过', '已驳回', '已完成'],
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: '#e5e7eb',
            width: 1,
            type: 'solid'
          }
        }
      },
      series: [{
        name: '申请数量',
        type: 'bar',
        data: [
          { value: statusCount.pending, itemStyle: { color: '#ff6b6b' } },
          { value: statusCount.approved, itemStyle: { color: '#4ecdc4' } },
          { value: statusCount.rejected, itemStyle: { color: '#ffa502' } },
          { value: statusCount.completed, itemStyle: { color: '#2c5530' } }
        ],
        barWidth: '60%'
      }]
    }
  },

  // 活动状态分布图（饼图）
  getActivityStatusChartOption() {
    const activities = this.data.chartData.activities || []
    const statusCount = {
      'upcoming': 0,
      'active': 0,
      'completed': 0,
      'cancelled': 0
    }
    
    activities.forEach(activity => {
      const status = activity.status || 'upcoming'
      if (statusCount.hasOwnProperty(status)) {
        statusCount[status]++
      }
    })
    
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        orient: 'horizontal',
        bottom: '5%',
        left: 'center',
        itemGap: 25,
        itemWidth: 12,
        itemHeight: 12,
        textStyle: {
          fontSize: 12,
          color: '#333',
          fontWeight: 'normal'
        }
      },
      series: [{
        name: '活动状态',
        type: 'pie',
        radius: ['40%', '68%'],
        center: ['50%', '42%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          { value: statusCount.upcoming, name: '即将开始', itemStyle: { color: '#4ecdc4' } },
          { value: statusCount.active, name: '进行中', itemStyle: { color: '#2c5530' } },
          { value: statusCount.completed, name: '已结束', itemStyle: { color: '#6b8e6b' } },
          { value: statusCount.cancelled, name: '已取消', itemStyle: { color: '#95a5a6' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          scale: true,
          scaleSize: 5
        }
      }]
    }
  },

  // 投诉类型分布图（饼图）
  getComplaintTypeChartOption() {
    const stats = this.data.chartData.complaintStats || {}
    // 适配后端返回的数据结构：byType.service, byType.efficiency, byType.facility, byType.other
    const typeCount = {
      'service': (stats.byType && stats.byType.service) || 0,
      'efficiency': (stats.byType && stats.byType.efficiency) || 0,
      'facility': (stats.byType && stats.byType.facility) || 0,
      'other': (stats.byType && stats.byType.other) || 0
    }
    
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        orient: 'vertical',
        right: '8%',
        top: 'center',
        itemGap: 25,
        itemWidth: 16,
        itemHeight: 16,
        textStyle: {
          fontSize: 14,
          color: '#333',
          fontWeight: 'normal',
          lineHeight: 20
        },
        formatter: function(name) {
          return name;
        }
      },
      series: [{
        name: '投诉类型',
        type: 'pie',
        radius: ['35%', '60%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          { value: typeCount.service, name: '服务态度', itemStyle: { color: '#ff6b6b' } },
          { value: typeCount.efficiency, name: '办事效率', itemStyle: { color: '#4ecdc4' } },
          { value: typeCount.facility, name: '设施环境', itemStyle: { color: '#ffa502' } },
          { value: typeCount.other, name: '其他建议', itemStyle: { color: '#6b8e6b' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          scale: true,
          scaleSize: 5
        }
      }]
    }
  },

  // 月度活动趋势图（折线图）
  getMonthlyActivityChartOption() {
    const activities = this.data.chartData.activities || []
    const monthlyData = {}
    
    activities.forEach(activity => {
      if (activity.startDate) {
        const month = activity.startDate.substring(0, 7) // YYYY-MM
        monthlyData[month] = (monthlyData[month] || 0) + 1
      }
    })
    
    // 获取最近6个月的数据
    const months = []
    const values = []
    const now = new Date()
    
    for (let i = 5; i >= 0; i--) {
      const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
      const monthLabel = `${date.getMonth() + 1}月`
      months.push(monthLabel)
      values.push(monthlyData[monthKey] || 0)
    }
    
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '8%',
        right: '5%',
        top: '12%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: '#e5e7eb',
            width: 1,
            type: 'solid'
          }
        }
      },
      series: [{
        name: '活动数量',
        type: 'line',
        smooth: true,
        data: values,
        itemStyle: {
          color: '#2c5530'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(44, 85, 48, 0.3)' },
              { offset: 1, color: 'rgba(44, 85, 48, 0.1)' }
            ]
          }
        }
      }]
    }
  },

  // 投诉处理效率图（柱状图）
  getComplaintProcessingChartOption() {
    const stats = this.data.chartData.complaintStats || {}
    // 适配后端返回的数据结构：pending, processing, completed
    const pendingCount = stats.pending || 0
    const processingCount = stats.processing || 0
    const completedCount = stats.completed || 0
    
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '8%',
        right: '5%',
        top: '12%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['待处理', '处理中', '已完成'],
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: '#e5e7eb',
            width: 1,
            type: 'solid'
          }
        }
      },
      series: [{
        name: '投诉数量',
        type: 'bar',
        data: [
          { value: pendingCount, itemStyle: { color: '#ff6b6b' } },
          { value: processingCount, itemStyle: { color: '#4ecdc4' } },
          { value: completedCount, itemStyle: { color: '#2c5530' } }
        ],
        barWidth: '60%'
      }]
    }
  },

  // 服务申请趋势图（折线图）
  getServiceTrendChartOption() {
    const applications = this.data.chartData.serviceApplications || []
    const monthlyData = {}
    
    applications.forEach(app => {
      if (app.applyTime) {
        const month = app.applyTime.substring(0, 7) // YYYY-MM
        monthlyData[month] = (monthlyData[month] || 0) + 1
      }
    })
    
    // 获取最近6个月的数据
    const months = []
    const values = []
    const now = new Date()
    
    for (let i = 5; i >= 0; i--) {
      const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
      const monthLabel = `${date.getMonth() + 1}月`
      months.push(monthLabel)
      values.push(monthlyData[monthKey] || 0)
    }
    
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '8%',
        right: '5%',
        top: '12%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: '#e5e7eb',
            width: 1,
            type: 'solid'
          }
        }
      },
      series: [{
        name: '申请数量',
        type: 'line',
        smooth: true,
        data: values,
        itemStyle: {
          color: '#4a7c59'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(74, 124, 89, 0.3)' },
              { offset: 1, color: 'rgba(74, 124, 89, 0.1)' }
            ]
          }
        }
      }]
    }
  },

  // 数据综合对比图（柱状图）
  getComprehensiveComparisonChartOption() {
    const userCount = this.data.chartData.userCount || {}
    const activities = this.data.chartData.activities || []
    const applications = this.data.chartData.serviceApplications || []
    const complaintStats = this.data.chartData.complaintStats || {}
    
    // 计算本月新增活动数量
    const currentMonthActivities = this.getCurrentMonthActivities(activities)
    // 计算本月新增申请数量
    const currentMonthApplications = this.getCurrentMonthApplications(applications)
    // 本月新增投诉数量（使用后端返回的数据）
    const currentMonthComplaints = (complaintStats.byTime && complaintStats.byTime.thisMonth) || 0
    
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(50, 50, 50, 0.9)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        data: ['总数', '本月新增'],
        top: '8%',
        textStyle: {
          fontSize: 13,
          color: '#333'
        },
        itemGap: 30
      },
      grid: {
        left: '8%',
        right: '5%',
        top: '20%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['用户', '活动', '服务申请', '投诉建议'],
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: { color: '#999' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: '#e5e7eb',
            width: 1,
            type: 'solid'
          }
        }
      },
      series: [
        {
          name: '总数',
          type: 'bar',
          data: [
            userCount.totalCount || 0,
            activities.length,
            applications.length,
            complaintStats.total || 0
          ],
          itemStyle: {
            color: '#2c5530'
          }
        },
        {
          name: '本月新增',
          type: 'bar',
          data: [
            userCount.todayNewTotalCount || 0,
            currentMonthActivities,
            currentMonthApplications,
            currentMonthComplaints
          ],
          itemStyle: {
            color: '#ffa502'
          }
        }
      ]
    }
  },

  // 获取本月活动数量
  getCurrentMonthActivities(activities) {
    const now = new Date()
    const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    return activities.filter(activity => {
      if (activity.startDate) {
        return activity.startDate.startsWith(currentMonth)
      }
      return false
    }).length
  },

  // 获取本月申请数量
  getCurrentMonthApplications(applications) {
    const now = new Date()
    const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    return applications.filter(app => {
      if (app.applyTime) {
        return app.applyTime.startsWith(currentMonth)
      }
      return false
    }).length
  },


  onShow() {
    // 页面显示时刷新数据
    if (this.data.chartData && Object.keys(this.data.chartData).length > 0) {
      this.loadChartData()
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadChartData().finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 强制刷新图表
  forceRefreshCharts() {
    console.log('强制刷新图表')
    this.loadChartData()
  }
})
